<?php

namespace app\common\model;


class Producer extends BaseModel
{
    protected $pk = 'producer_id';

    protected $autoWriteTimestamp = 'datetime';

    protected $insert = ['create_by', 'update_by'];

    protected $update = ['update_by'];

    public static $STATUS = [
        self::IS_YES => '启用',
        self::IS_NO => '关闭'
    ];

    /**
     * 线上
     */
    const LINE_ON = 1;

    /**
     * 线下
     */
    const LINE_OFF = 0;

    /**
     * 代工厂
     */
    const LINE_AGENT = 2;

    /**
     * 中间商
     */
    const LINE_MIDD = 3;

    public static $LINE_TYPE = [
        self::LINE_ON => '线上',
        self::LINE_OFF => '线下',
        self::LINE_AGENT => '代工厂',
        self::LINE_MIDD => '中间商',
    ];

    protected function getPayTypeAttr($value)
    {
        return isset(FinancePayment::$PAY_TYPE[$value]) ? FinancePayment::$PAY_TYPE[$value] : $value;
    }

    protected function getTypeAttr($value)
    {
        return isset(self::$LINE_TYPE[$value]) ? self::$LINE_TYPE[$value] : $value;
    }

    /**
     * 采购供应商链接
     * @return \think\model\relation\HasMany
     * @date 2020/11/07
     * @author longli
     */
    public function productPurchase()
    {
        return $this->hasMany(ProductPurchase::class);
    }

    /**
     * 关联采购单
     * @return \think\model\relation\HasMany
     * @date 2020/11/07
     * @author longli
     */
    public function purchase()
    {
        return $this->hasMany(Purchase::class);
    }

    /**
     * 供应商名称是否存在
     * @param string $name 分类名
     * @return bool
     * @date 2020/09/11
     * @author longli
     */
    public static function hasByName($name)
    {
        return !!static::where(['name' => $name])->count();
    }

    /**
     * 通过名称获取供应商
     * @param string $name 分类名
     * @return static
     * @date 2020/09/11
     * @author longli
     */
    public static function getByName($name)
    {
        return static::where(['name' => $name])->find();
    }

    /**
     * 获取所有供应商
     * @return array|\PDOStatement|string|\think\Collection
     * @date 2020/09/15
     * @author longli
     */
    public static function getAll()
    {
        return static::where(['status' => self::IS_YES])->select();
    }

    /**
     * 添加供应商共采购金额
     * @param float $price 付款金额
     * @return bool
     * @date 2021/02/05
     * @author longli
     */
    public function addPrice($price = 0)
    {
        if($price == 0) return false;
        $this->total_price += $price < 0 && $this->total_price < abs($price)
            ? -$this->total_price
            : $price;
        return $this->save();
    }
}
